<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="责改号" prop="rectifyNo">
            <el-input v-model="formData.rectifyNo" disabled placeholder="请输入责改号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="营业执照类型" prop="businessType">
            <el-input v-model="formData.businessType" disabled placeholder="请输入营业执照类型" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" disabled placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
        <CaseSituation
          ref="caseSituationRef"
          v-model="formData"
          :disabled="disabled"
          :show="'案情说明, 证据证明, 违反条例, 处理依据, 陈述申辩'"
          :caseIsEdit="true"
          :stateIsEdit="true"
          :isEdit="true"
          :violationIsEdit="true" />
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch } from 'vue'
import {
  getHearingNotice,
  addHearingNotice,
  updateHearingNotice,
  getCaseList,
  getContent,
  previewPdf,
} from '@/api/hearingNotice/notice.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import CaseSituation from '@/components/CaseSituation/index.vue'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: undefined,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  rectifyNo: null,
  partyName: null,
  streetOfCompanyAddress: null,
  address: null,
  legalRepresentative: null,
  businessType: null,
  caseDesc: null,
  evidenceDesc: null,
  violationRegulations: null,
  statementDefense: null,
  handlingBasis: null,
  penaltyAdvanceNoticeId: null,
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  rectifyNo: [{ required: true, message: '责改号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  caseDesc: [{ required: true, message: '请输入案情说明', trigger: ['blur', 'change'] }],
  evidenceDesc: [{ required: true, message: '请输入证据证明', trigger: ['blur', 'change'] }],
  violationRegulations: [{ required: true, message: '请输入违反条例', trigger: ['blur', 'change'] }],
  statementDefense: [{ required: true, message: '请输入陈述申辩告知', trigger: ['blur', 'change'] }],
  handlingBasis: [{ required: true, message: '请输入处理依据', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  businessType: [{ required: true, message: '营业执照类型不能为空', trigger: ['blur', 'change'] }],
  unifiedSocialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  siteDescription: [{ required: true, message: '请输入检查情况', trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    rectifyNo: null,
    partyName: null,
    streetOfCompanyAddress: null,
    address: null,
    legalRepresentative: null,
    businessType: null,
    caseDesc: null,
    evidenceDesc: null,
    violationRegulations: null,
    statementDefense: null,
    handlingBasis: null,
    penaltyAdvanceNoticeId: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getHearingNotice(id)
      formData.value = res.data
      formData.value.siteDescription = formData.value.caseDesc
      formData.value.statementDefense = formData.value.pleadNotice
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.rectifyNo = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.businessType = ''
      formData.value.unifiedSocialCreditCode = ''
      formData.value.penaltyAdvanceNoticeId = ''
      formData.value.statementDefense = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      formData.value.violationRegulations = ''
      formData.value.evidenceDesc = ''
      formData.value.caseDesc = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const {
      partyName,
      partyId,
      legalRepresentative,
      businessType,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
    } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.businessType = businessType
    formData.value.unifiedSocialCreditCode = unifiedSocialCreditCode
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await getContent(val)
    formData.value.rectifyNo = res2.data.rectifyNo
    formData.value.caseDesc = res2.data.caseDesc
    formData.value.evidenceDesc = res2.data.evidenceDesc
    formData.value.violationRegulations = res2.data.violationRegulations
    formData.value.handlingBasis = res2.data.handlingBasis
    formData.value.penaltyAdvanceNoticeId = res2.data.penaltyAdvanceNoticeId
    formData.value.statementDefense = res2.data.pleadNotice
    formData.value.hearingNoticeApprovalId = res2.data.hearingNoticeApprovalId
    nextTick(() => {
      caseSituationRef.value.pullCaseDescOnly()
    })
    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = async (isPreview = false) => {
  return new Promise((resolve, reject) => {
    console.log('提交数据', formData.value)
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        let num = 0
        caseSituationRef.value.reasonSegments.forEach(item => {
          if (item.type === 'input' && !item.value) {
            num += 1
          }
        })
        if (num > 0) {
          ElMessage.error('请将催告理由填写完整')
          return false
        }
        num = 0
        caseSituationRef.value.handlerOpinionSegments.forEach(item => {
          if (item.type === 'input' && !item.value) {
            num += 1
          }
        })
        if (num > 0) {
          ElMessage.error('请将承办人意见填写完整')
          return false
        }
        formData.value.caseDesc = formData.value.siteDescription
        formData.value.pleadNotice = formData.value.statementDefense
        if (isPreview === true) {
          resolve(formData.value)
          return
        }
        let result
        if (formData.value.id) {
          result = await updateHearingNotice(formData.value)
        } else {
          result = await addHearingNotice(formData.value)
        }

        ElMessage.success('提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(() => {
        reject()
      })
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
